const actions = {
  addtocart(context, value) {
    context.commit('ADDTOCART', value)
  }
}

const mutations = {
  //添加到购物车
  ADDTOCART(state, value) {
    //查看是否购物车中是否有这个物品
    // 如果不存在， 则 findResult 为 undefined； 否则， 为查找到的商品信息对象
    let res = state.cart.find((x) => {
      return x.goods_id == value.goods_id
    })
    //如果没有，就直接添加
    if (!res) {
      state.cart.push(value)
    } else { //已经存在了，那就是将该物品数量加1
      res.goods_count++
    }
    //持久化存储
    this.commit('cart/SAVETOSTORAGE')
  },

  //持久化存储 —— 本地存储
  SAVETOSTORAGE(state, value) {
    uni.setStorageSync('cart', JSON.stringify(state.cart))
  },

  //更新购物车商品勾选状态
  updateGoodsState(state, goods) {
    let res = state.cart.find(x => x.goods_id === goods.goods_id)
    if (res) {
      //修改购物车中商品选中状态
      res.goods_state = goods.goods_state
      this.commit('cart/SAVETOSTORAGE')
    }
  },

  //更新购物车商品数量
  updateGoodsNum(state, goods) {
    let res = state.cart.find(x => x.goods_id === goods.goods_id)
    if (res) {
      //修改购物车中商品数量
      res.goods_count = goods.goods_count
      this.commit('cart/SAVETOSTORAGE')
    }
  },
  //删除购物车中的商品
  deleteGoods(state, goods) {
    let newCart = state.cart.filter((x) => {
      return x.goods_id != goods.goods_id
    })
    state.cart = newCart
    this.commit('cart/SAVETOSTORAGE')
  },

  //更改勾选购物车的状态
  selectAllGoods(state, goods) {
    state.cart = goods
    //本地存储
    this.commit('cart/SAVETOSTORAGE')
  }
}

const getters = {
  //购物车所有商品数据
  totals(state) {
    //以购物车中不同物品的数量来进行展示
    return state.cart.length
  },

  //被选择商品的数量
  checkedCount(state) {
    let count = 0
    state.cart.forEach((item) => {
      if (item.goods_state === true) {
        count++
      }
    })
    return count
  },

  //统计被选择商品的总价钱
  checkedGoodsAmount(state) {
    return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count * item.goods_price,
      0).toFixed(2)
  }
}

const state = {
  // 购物车的数组，用来存储购物车中每个商品的信息对象
  // 每个商品的信息对象，都包含如下 6 个属性：
  // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
  cart: JSON.parse(uni.getStorageSync('cart') || '[]'),

}

export default {
  namespaced: true,
  actions,
  mutations,
  getters,
  state
}
